package top.huhuiyu.springboot2.study.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.huhuiyu.springboot2.study.base.BaseResult;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 胡辉煜
 */
//@ControllerAdvice是全局的控制器异常处理
@ControllerAdvice
@Slf4j
public class AppExceptionHandler {

  @ExceptionHandler(AppException.class)
  @ResponseBody
  public BaseResult handle(AppException ex) {
    log.debug("应用异常处理:{}", ex.getMessage());
    return BaseResult.fail(ex.getMessage());
  }

  @ExceptionHandler(BindException.class)
  @ResponseBody
  public BaseResult handle(BindException ex) {
    // 数据校验异常处理
    List<ObjectError> errors = ex.getAllErrors();
    StringBuilder sb = new StringBuilder();
    errors.forEach(error -> {
      sb.append(error.getDefaultMessage()).append(";");
    });
    return BaseResult.fail(sb.toString());
  }

  @ExceptionHandler(MethodArgumentNotValidException.class)
  @ResponseBody
  public BaseResult handle(MethodArgumentNotValidException ex) {
    // 数据校验异常处理
    List<ObjectError> errors = ex.getAllErrors();
    StringBuilder sb = new StringBuilder();
    errors.forEach(error -> {
      sb.append(error.getDefaultMessage()).append(";");
    });
    return BaseResult.fail(sb.toString());
  }

  @ExceptionHandler(SQLException.class)
  @ResponseBody
  public BaseResult handle(SQLException ex) {
    log.error("数据库异常处理", ex);
    return BaseResult.fail("数据库异常");
  }

  @ExceptionHandler(DataAccessException.class)
  @ResponseBody
  public BaseResult handle(DataAccessException ex) {
    log.error("数据操作异常处理", ex);
    return BaseResult.fail("数据操作异常");
  }

  @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
  @ResponseBody
  public BaseResult handle(HttpRequestMethodNotSupportedException ex) {
    return BaseResult.fail("请求的方式不正确");
  }

  @ExceptionHandler(Exception.class)
  @ResponseBody
  public BaseResult handle(Exception ex) {
    // 所有不在列表中的异常都会进到这里，原因是：Exception是所有异常的父类
    log.debug("统一异常处理:{}", ex.getMessage());
    log.error("", ex);
    return BaseResult.fail(ex.getMessage());
  }

}
